<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Python Code Upload</title>
    <style>
        :root {
            --primary-color: #4a90e2;
            --secondary-color: #f5f5f5;
            --text-color: #333;
            --border-radius: 8px;
        }

        body {
            font-family: 'Segoe UI', Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f0f2f5;
            color: var(--text-color);
            line-height: 1.6;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        h1, h2 {
            color: var(--primary-color);
            margin-bottom: 1.5rem;
        }

        form {
            background: white;
            padding: 2rem;
            border-radius: var(--border-radius);
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 2rem;
        }

        input[type="text"], textarea {
            width: 100%;
            padding: 10px;
            margin: 8px 0;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            box-sizing: border-box;
            font-size: 14px;
        }
        textarea {
            min-height: 200px;
            resize: vertical;
        }

        button {
            background-color: var(--primary-color);
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #357abd;
        }

        .script-list {
            background: white;
            padding: 2rem;
            border-radius: var(--border-radius);
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .script-item {
            padding: 1rem;
            border-bottom: 1px solid #eee;
            transition: background-color 0.3s;
        }

        .script-item:hover {
            background-color: var(--secondary-color);
        }

        .script-item:last-child {
            border-bottom: none;
        }

        .checkbox-wrapper {
            display: flex;
            align-items: center;
            gap: 8px;
            margin: 1rem 0;
        }

        #loadMore {
            margin-top: 1rem;
            width: 100%;
            background-color: #f8f9fa;
            color: var(--text-color);
            border: 1px solid #ddd;
        }
        #loadMore:hover {
            background-color: #e9ecef;
        }

        .search-box {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
        }

        .search-input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            font-size: 14px;
        }

        .search-button {
            padding: 0px 20px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .search-button:hover {
            background-color: #357abd;
        }

        .action-buttons {
            margin-top: 15px;
            display: flex;
            gap: 10px;
        }

        .execute-btn {
            background-color: #28a745;
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .execute-btn:hover {
            background-color: #218838;
        }

        .settings-btn {
            background-color: #6c757d;
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .settings-btn:hover {
            background-color: #5a6268;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            display: none;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            position: relative;
            background-color: white;
            margin: auto;
            padding: 20px;
            width: 80%;
            max-width: 800px;
            max-height: 80vh;
            border-radius: var(--border-radius);
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow-y: auto;
        }

        .modal-content::-webkit-scrollbar {
            width: 8px;
        }

        .modal-content::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }

        .modal-content::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }

        .modal-content::-webkit-scrollbar-thumb:hover {
            background: #555;
        }

        #logList {
            max-height: calc(60vh - 100px);
            overflow-y: auto;
            margin: 15px 0;
        }

        .pagination {
            margin-top: 20px;
            padding-top: 15px;
            border-top: 1px solid #eee;
            position: sticky;
            bottom: 0;
            background: white;
        }

        .close-modal {
            position: absolute;
            right: 15px;
            top: 15px;
            font-size: 24px;
            cursor: pointer;
            color: #666;
            z-index: 1;
        }

        .close-modal:hover {
            color: #333;
        }

        .modal-content h2 {
            margin-top: 0;
            padding-right: 30px;
        }

        /* 模态框表单样式优化 */
        .modal-form {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .modal-form label {
            font-weight: 500;
            color: #333;
            margin-bottom: 5px;
        }

        .modal-form input {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            font-size: 14px;
            transition: border-color 0.3s;
        }

        .modal-form input:focus {
            border-color: var(--primary-color);
            outline: none;
        }

        .save-btn {
            background-color: var(--primary-color);
            color: white;
            padding: 12px;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-size: 16px;
            margin-top: 10px;
            transition: background-color 0.3s;
        }

        .save-btn:hover {
            background-color: #357abd;
        }

        /* 日志列表样式优化 */
        .log-item {
            padding: 20px;
            border: 1px solid #eee;
            border-radius: var(--border-radius);
            margin-bottom: 15px;
            background-color: #fff;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .log-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .log-status {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 10px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .log-status.success {
            color: #28a745;
        }

        .log-status.error {
            color: #dc3545;
        }

        .log-details {
            display: grid;
            gap: 8px;
            color: #555;
            font-size: 14px;
        }

        .log-details div {
            display: grid;
            grid-template-columns: 120px 1fr;
            gap: 10px;
        }

        .log-details div::before {
            content: attr(data-label);
            color: #666;
            font-weight: 500;
        }

        /* 分页样式优化 */
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 20px;
            padding: 15px;
            background: white;
            border-top: 1px solid #eee;
        }

        .pagination button {
            padding: 8px 16px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .pagination button:hover:not(:disabled) {
            background-color: #357abd;
        }

        .pagination button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }

        #pageInfo {
            font-size: 14px;
            color: #666;
            font-weight: 500;
        }

        /* 设置模态框内容区域固定高度，不需要滚动 */
        /*#settingsModal .modal-content {*/
        /*    max-height: none;*/
        /*    overflow: visible;*/
        /*}*/

        .api-list-btn {
            background-color: var(--primary-color);
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .api-list-btn:hover {
            background-color: var(--primary-color);
        }

        .api-item {
            background: white;
            border-radius: 12px;
            padding: 24px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

        .api-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        .api-name {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }

        .api-status {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 500;
        }

        .api-status.success {
            background-color: #e6f6f1;
            color: #00a870;
        }

        .api-status.error {
            background-color: #ffefef;
            color: #ff4d4f;
        }

        .api-detail-row {
            display: grid;
            grid-template-columns: 140px 1fr;
            gap: 16px;
            padding: 12px 0;
            align-items: center;
        }

        .api-detail-row:not(:last-child) {
            border-bottom: 1px solid #f0f0f0;
        }

        .api-detail-row span:first-child {
            color: #666;
            font-size: 14px;
        }

        .api-detail-row span:last-child {
            color: #333;
            font-size: 14px;
            word-break: break-all;
        }

        .button-group {
            display: flex;
            gap: 8px;
        }

        .copy-btn, .view-btn {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 6px;
            flex: 1; /* 让按钮占据相同的宽度 */
            background-color: #a09d9d; /* 默认背景色为灰色 */
            color: white; /* 字体颜色 */
        }


        .api-timestamp {
            color: #8c8c8c;
            font-size: 13px;
        }

        .api-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin: 8px 0;
        }

        .api-tag {
            background-color: #e9ecef;
            color: #495057;
            padding: 4px 12px;
            border-radius: 16px;
            font-size: 13px;
            display: inline-block;
            border: 1px solid #dee2e6;
        }

        /* 添加标签页样式 */
        .tabs {
            width: 100%;
            margin-bottom: 20px;
        }

        .tab-buttons {
            display: flex;
            gap: 2px;
            margin-bottom: -1px;
        }

        .tab-button {
            padding: 12px 24px;
            background-color: #f0f2f5;
            border: 1px solid #ddd;
            border-bottom: none;
            border-radius: 8px 8px 0 0;
            cursor: pointer;
            font-size: 20px;
            color: #666;
            transition: all 0.3s;
            font-weight: 500;
        }

        .tab-button.active {
            background-color: white;
            color: var(--primary-color);
            border-bottom: 1px solid white;
            font-weight: 600;
            font-size: 22px;
        }

        .tab-content {
            display: none;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 0 8px 8px 8px;
            background-color: white;
        }

        .tab-content.active {
            display: block;
        }

        /* 批量API请求模态框样式 */
        .batch-api-item {
            position: relative;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            background: #f8f9fa;
            margin-bottom: 10px;
            display: flex;
            gap: 10px;  /* 添加间距 */
        }

        .batch-api-input {
            flex: 1;  /* 让输入框占据剩余空间 */
            min-height: 60px;  /* 设置最小高度 */
            resize: vertical;  /* 允许垂直拉伸 */
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            font-family: monospace;  /* 使用等宽字体 */
            font-size: 14px;
        }

        .batch-api-controls {
            display: flex;
            flex-direction: column;  /* 按钮垂直排列 */
            gap: 5px;
        }

        .add-api-btn, .remove-api-btn {
            padding: 5px 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            width: 30px;  /* 固定按钮宽度 */
            height: 30px;  /* 固定按钮高度 */
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .add-api-btn {
            background-color: #28a745;
            color: white;
        }

        .remove-api-btn {
            background-color: #dc3545;
            color: white;
        }

        /* 添加标签样式 */
        .batch-api-form label {
            display: block;
            font-weight: 500;
            margin-bottom: 10px;
            color: #333;
            font-size: 16px;
        }
        

        #viewContentBody {
            font-family: monospace;
            font-size: 14px;
            line-height: 1.5;
        }

        /* 美化下拉选择框 */
        select {
            width: 100%;
            padding: 10px;
            margin: 8px 0;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            box-sizing: border-box;
            font-size: 14px;
            background-color: white;
            appearance: none; /* 去掉默认样式 */
            background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 10 10"><polygon points="0,0 10,0 5,5" fill="%234a90e2"/></svg>'); /* 自定义下拉箭头 */
            background-repeat: no-repeat;
            background-position: right 10px center;
            background-size: 10px;
        }

        /* 美化下拉选择框的聚焦状态 */
        select:focus {
            border-color: var(--primary-color);
            outline: none;
        }

        .script-title {
            color: var(--primary-color);
            font-size: 18px;
            font-weight: 600;
            margin: 0 0 20px 0;
            padding-bottom: 12px;
            border-bottom: 1px solid #eee;
        }

        .script-info-container {
            margin-bottom: 20px;
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 16px;
        }

        .info-item {
            display: flex;
            align-items: flex-start;
            gap: 12px;
        }

        .info-item.full-width {
            grid-column: 1 / -1;
        }

        .info-label {
            color: #666;
            font-size: 14px;
            min-width: 120px;
            flex-shrink: 0;
        }

        .info-value {
            font-size: 14px;
            flex: 1;
        }
        .info-valueV1 {
            font-size: 16px;
            font-weight: bold;
            flex: 1;
        }

        .api-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            flex: 1;
        }

        .api-tag {
            background-color: #f5f7fa;
            border: 1px solid #e4e7ed;
            border-radius: 4px;
            padding: 4px 12px;
            font-size: 13px;
            color: #606266;
        }

        .no-data {
            color: #999;
            font-style: italic;
        }

        .action-buttons {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            padding-top: 20px;
            border-top: 1px solid #eee;
        }

        .action-buttons button {
            min-width: 100px;
            padding: 8px 16px;
            border-radius: 4px;
            font-size: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }

        .action-buttons button:hover:not(:disabled) {
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .settings-modal {
            background: white;
            border-radius: 16px;
            padding: 32px;
            width: 90%;
            max-width: 560px;
            box-shadow: 0 4px 24px rgba(0, 0, 0, 0.12);
            position: relative;
        }

        .settings-title {
            color: #2c3e50;
            font-size: 24px;
            font-weight: 600;
            margin: 0 0 32px 0;
            padding-bottom: 16px;
            border-bottom: 2px solid #eef2f7;
        }

        .settings-form {
            display: flex;
            flex-direction: column;
            gap: 24px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .form-group label {
            color: #4a5568;
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 4px;
        }

        .form-input,
        .form-select {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            color: #2d3748;
            transition: all 0.2s ease;
            background-color: white;
        }

        .form-input:hover,
        .form-select:hover {
            border-color: #cbd5e0;
        }

        .form-input:focus,
        .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.15);
            outline: none;
        }

        .form-input::placeholder {
            color: #a0aec0;
        }

        .form-select {
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%234a5568' d='M6 8.825L1.175 4 2.238 2.938 6 6.7l3.763-3.763L10.825 4z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 16px center;
            padding-right: 40px;
        }

        .save-btn {
            background-color: var(--primary-color);
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            margin-top: 8px;
            width: 100%;
        }

        .save-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(66, 153, 225, 0.2);
        }

        .save-btn:active {
            transform: translateY(0);
        }

        .close-modal {
            position: absolute;
            top: 24px;
            right: 24px;
            font-size: 24px;
            color: #a0aec0;
            cursor: pointer;
            transition: color 0.2s ease;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            background: #f7fafc;
        }

        .close-modal:hover {
            color: #4a5568;
            background: #edf2f7;
        }
        .form-input-disabled {
            background-color: #f8f9fa;
            color: #6c757d;
            cursor: not-allowed;
            border-color: #e2e8f0;
        }

        /* 添加动画效果 */
        .modal {
            animation: fadeIn 0.2s ease;
        }

        .modal-content {
            animation: slideIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* 响应式适配 */
        @media (max-width: 640px) {
            .settings-modal {
                padding: 24px;
                width: 95%;
            }

            .settings-title {
                font-size: 20px;
                margin-bottom: 24px;
            }

            .form-group {
                gap: 6px;
            }
        }

        .form-input-short {
            max-width: 455px; /* 或者其他合适的宽度 */
            width: 100%;
        }

        /* 修复模态框滚动问题 */
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: none;
            align-items: flex-start; /* 改为顶部对齐 */
            justify-content: center;
            padding: 20px;
            overflow-y: auto; /* 允许模态框内容滚动 */
            z-index: 1000;
        }

        /* 批量API请求模态框样式优化 */
        .batch-modal {
            padding: 0;
            max-width: 800px;
            width: 90%;
            max-height: 90vh;
            background: #fff;
            border-radius: 16px;
            display: flex;
            flex-direction: column;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
        }

        .batch-modal-header {
            background: linear-gradient(135deg, var(--primary-color), #357abd);
            padding: 24px 32px;
            border-radius: 16px 16px 0 0;
            flex-shrink: 0;
        }

        .batch-modal-header h2 {
            color: #fff;
            margin: 0;
            font-size: 24px;
            font-weight: 600;
            letter-spacing: 0.5px;
        }

        .subtitle {
            color: rgba(255,255,255,0.8);
            margin: 8px 0 0;
            font-size: 14px;
        }

        .batch-api-form {
            padding: 24px 32px;
            overflow-y: auto;
            flex: 1;
        }

        .form-group {
            margin-bottom: 24px;
        }

        .form-group label {
            display: block;
            color: #2c3e50;
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 8px;
        }

        .label-hint {
            color: #94a3b8;
            font-size: 13px;
            font-weight: normal;
        }

        .batch-items-container {
            display: flex;
            flex-direction: column;
            gap: 16px;
        }

        .batch-api-item {
            position: relative;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            background: #f8f9fa;
            margin-bottom: 10px;
            display: flex;
            gap: 10px;  /* 添加间距 */
        }

        .batch-api-input {
            flex: 1;  /* 让输入框占据剩余空间 */
            min-height: 60px;  /* 设置最小高度 */
            resize: vertical;  /* 允许垂直拉伸 */
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            font-family: monospace;  /* 使用等宽字体 */
            font-size: 14px;
        }

        .batch-api-controls {
            display: flex;
            flex-direction: column;  /* 按钮垂直排列 */
            gap: 5px;
        }

        .add-api-btn, .remove-api-btn {
            padding: 5px 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            width: 30px;  /* 固定按钮宽度 */
            height: 30px;  /* 固定按钮高度 */
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .add-api-btn {
            background-color: #28a745;
            color: white;
        }

        .remove-api-btn {
            background-color: #dc3545;
            color: white;
        }

        .execute-batch-btn {
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            flex: 1;
        }

        .execute-batch-btn:hover {
            background-color: #0069d9;
        }

        .form-input-disabled {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 12px;
            width: 100%;
            color: #64748b;
            font-size: 14px;
        }

        /* 响应式适配 */
        @media (max-width: 640px) {
            .batch-modal {
                width: 95%;
                max-height: 95vh;
            }
            
            .batch-modal-header {
                padding: 20px 24px;
            }
            
            .batch-api-form {
                padding: 20px 24px;
            }
            
            .batch-api-item {
                flex-direction: column;
            }
            
            .batch-api-controls {
                flex-direction: row;
                justify-content: flex-end;
            }
        }

        /* 批量API模态框样式 */
        .batch-modal {
            max-width: 800px;
        }

        .batch-modal-header {
            margin-bottom: 20px;
        }

        .batch-modal-header .subtitle {
            color: #666;
            margin-top: 5px;
        }

        .batch-api-form {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .batch-items-container {
            display: flex;
            flex-direction: column;
            gap: 10px;
            max-height: 400px;
            overflow-y: auto;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 8px;
        }

        .batch-api-item {
            display: flex;
            gap: 10px;
        }

        .batch-api-input {
            flex: 1;
            min-height: 100px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-family: monospace;
            resize: vertical;
        }

        .batch-api-controls {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .add-api-btn, .remove-api-btn {
            width: 30px;
            height: 30px;
            border: none;
            border-radius: 50%;
            color: white;
            font-size: 18px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .add-api-btn {
            background-color: #28a745;
        }

        .remove-api-btn {
            background-color: #dc3545;
        }

        .execute-batch-btn {
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            flex: 1;
        }

        .execute-batch-btn:hover {
            background-color: #0069d9;
        }

        /* 新增样式 */
        .button-group {
            display: flex;
            justify-content: space-between;
            gap: 15px;
            margin-top: 20px;
        }

        .btn-icon {
            font-size: 18px;
            margin-right: 5px;
        }

        .btn-text {
            font-weight: 500;
        }

        .save-params-btn {
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            flex: 1;
        }

        .save-params-btn:hover {
            background-color: #218838;
        }

        .execute-batch-btn {
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            flex: 1;
        }

        .execute-batch-btn:hover {
            background-color: #0069d9;
        }

        .params-select-container {
            display: flex;
            gap: 10px;
        }

        .params-select {
            flex: 1;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .refresh-btn {
            width: 36px;
            height: 36px;
            background-color: #17a2b8;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .refresh-btn:hover {
            background-color: #138496;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="tabs">
        <div class="tab-buttons">
            <button class="tab-button active" onclick="switchTab(0)">Sloth(手动版)</button>
            <button class="tab-button" onclick="switchTab(1)">Sloth(AI版)</button>
            <button class="tab-button" onclick="switchTab(2)">Sloth(智能体)</button>
        </div>

        <!-- Tab 1 内容 -->
        <div class="tab-content active">

            <!-- 新增获取脚本区域 -->
            <div class="script-gen-box" style="margin-bottom: 20px;background: white;
            padding: 2rem;
            border-radius: var(--border-radius);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 2rem">
                <input
                    type="text"
                    id="scriptUrl"
                    placeholder="请输入URL..."
                    class="script-url-input"
                >
                <button id="generateScript" class="generate-btn" style="margin-top: 20px;">获取脚本</button>
            </div>

            <div style="margin-top: 20px;">
                <form id="uploadForm" action="http://127.0.0.1:8080/api/upload" method="post">
                    <label for="filename">脚本名称:</label>
                    <input type="text" name="filename" placeholder='请输入脚本名称' required>
                    <div id="filenameError" style="color: red;"></div>

                    <label for="code" style="margin-top: 50px;">Python 代码:</label><br>
                    <textarea name="code" rows="10" cols="30" placeholder="请输入Python脚本代码..." required></textarea><br><br>

                    <div style="display: flex; flex-wrap: wrap; gap: 20px; margin-bottom: 20px;">
                        <div style="display: flex; align-items: center; min-width: 150px;">
                            <label for="set_trace" style="margin-right: 5px; white-space: nowrap;">启用追踪:</label>
                            <input type="checkbox" name="setTrace" value="true" checked>
                        </div>
                        <div style="display: flex; align-items: center; min-width: 150px;">
                            <label for="isPrivate" style="margin-right: 5px; white-space: nowrap;">私有:</label>
                            <input type="checkbox" name="isPrivate" value="true" checked>
                        </div>

                        <div style="display: flex; align-items: center; min-width: 150px;">
                            <label for="gen_login" style="margin-right: 5px; white-space: nowrap;">生成登录信息:</label>
                            <input type="checkbox" id="gen_login" name="genLogin" value="true">
                        </div>

                        <div style="display: flex; align-items: center; min-width: 150px;">
                            <label for="use_login" style="margin-right: 5px; white-space: nowrap;">使用登录信息:</label>
                            <input type="checkbox" id="use_login" name="useLogin" value="true">
                        </div>
                    </div>

                    <button type="button" onclick="validateFilenameBeforeSubmit()">生成脚本文件</button>
                    <button type="button" id="generateApiFile" style="margin-left: 10px;" onclick="validateApiFileName()">生成脚本API文件</button>
                </form>
            </div>

            <div class="script-list">
                <h2>脚本文件列表</h2>
                <div class="search-box">
                    <input
                        type="text"
                        id="searchScriptName"
                        placeholder="请输入脚本名称..."
                        class="search-input"
                    >
                    <button id="searchButton" class="search-button">搜索</button>
                </div>
                <div id="scriptData"></div>
                <button id="loadMore">加载更多</button>
            </div>
        </div>

        <!-- Tab 2 内容 -->
        <div class="tab-content">
            <iframe
                id="aiAssistantFrame"
                src="http://127.0.0.1:7788/"
                style="width: 100%; height: 800px; border: none; border-radius: 8px;"
            ></iframe>
        </div>

        <!-- Tab 3 内容 -->
        <div class="tab-content">
            <iframe
                    id="aiAssistantFrame2"
                    src="http://localhost:42110/"
                    style="width: 100%; height: 800px; border: none; border-radius: 8px;"
            ></iframe>
        </div>
    </div>
</div>

<!-- 修改设置模态框的结构 -->
<div id="settingsModal" class="modal">
    <div class="modal-content settings-modal">
        <span class="close-modal" onclick="closeSettingsModal()">&times;</span>
        <h2 class="settings-title">设置</h2>
        <form id="settingsForm" class="settings-form">
            <input type="hidden" id="scriptId">

            <div class="form-group">
                <label for="modalScriptName">脚本名称</label>
                <div class="input-wrapper">
                    <input type="text" id="modalScriptName" class="form-input form-input-disabled" required readonly>
                    <div class="input-overlay" title="脚本名称不可修改"></div>
                </div>
            </div>

            <div class="form-group">
                <label for="modalExecuteMode">执行方式</label>
                <select id="modalExecuteMode" class="form-select" required onchange="toggleExecuteTimeInput()">
                    <option value="specified">按指定时间执行</option>
                    <option value="cycle">按周期循环执行</option>
                </select>
            </div>

            <div class="form-group" id="specifiedTimeGroup">
                <label for="modalExecuteTime">执行时间</label>
                <input type="datetime-local" id="modalExecuteTime" class="form-input form-input-short" step="1">
            </div>

            <div class="form-group" id="cycleTimeGroup" style="display: none;">
                <label for="modalCycleTime">执行周期(分钟)</label>
                <input type="number" id="modalCycleTime" class="form-input form-input-short" min="1" placeholder="请输入执行周期">
            </div>

            <div class="form-group">
                <label for="modalSendEmail">发送邮箱</label>
                <input type="email" id="modalSendEmail" class="form-input form-input-short" placeholder="请输入邮箱地址">
            </div>

            <div class="form-group">
                <label for="modalNeedApi">指定API前缀</label>
                <input type="text" id="modalNeedApi" class="form-input">
            </div>

            <div class="form-group">
                <label for="modalFilteredApis">所需API集合</label>
                <input type="text" id="modalFilteredApis" class="form-input">
            </div>

            <div class="form-group">
                <label for="modalDeleteApis">过滤API集合</label>
                <input type="text" id="modalDeleteApis" class="form-input">
            </div>

            <button type="submit" class="save-btn">保存设置</button>
        </form>
    </div>
</div>

<!-- 添加日志模态框 -->
<div id="logModal" class="modal">
    <div class="modal-content" style="max-width: 900px;">
        <span class="close-modal" onclick="closeLogModal()">&times;</span>
        <h2>执行日志</h2>
        <div id="logList"></div>
        <div class="pagination">
            <button id="prevPage" onclick="changePage(-1)">上一页</button>
            <span id="pageInfo">第 1 页</span>
            <button id="nextPage" onclick="changePage(1)">下一页</button>
        </div>
    </div>
</div>

<!-- 添加接口列表模态框 -->
<div id="apiModal" class="modal">
    <div class="modal-content" style="max-width: 900px; overflow: hidden;">
        <span class="close-modal" onclick="closeApiModal()">&times;</span>
        <h2>接口列表</h2>
        <div style="height: 60vh;overflow: hidden auto">
        <div id="apiList"></div>
    </div>
        <div class="pagination">
            <button id="apiPrevPage" onclick="changeApiPage(-1)">上一页</button>
            <span id="apiPageInfo">第 1 页</span>
            <button id="apiNextPage" onclick="changeApiPage(1)">下一页</button>
        </div>
    </div>
</div>

<!-- 添加批量API请求模态框 -->
<div id="batchApiModal" class="modal">
    <div class="modal-content batch-modal">
        <span class="close-modal" onclick="closeBatchApiModal()">&times;</span>
        <div class="batch-modal-header">
            <h2>脚本模拟</h2>
            <p class="subtitle">批量执行API请求</p>
        </div>
        
        <form id="batchApiForm" class="batch-api-form">
            <div class="form-group">
                <label for="scriptName">脚本名称</label>
                <input 
                    type="text" 
                    id="scriptName" 
                    required 
                    class="modal-form-input form-input-disabled" 
                    readonly
                >
            </div>

            <!-- 添加参数集选择下拉框 -->
            <div class="form-group">
                <label for="paramsSelect">参数集</label>
                <div class="params-select-container">
                    <select id="paramsSelect" class="params-select">
                        <option value="">-- 选择已保存的参数集 --</option>
                    </select>
                    <button type="button" class="refresh-btn" onclick="loadBatchParams()">
                        <span>🔄</span>
                    </button>
                </div>
            </div>

            <!-- 添加参数集名称输入框 -->
            <div class="form-group">
                <label for="paramsName">参数集名称</label>
                <input
                    type="text"
                    id="paramsName"
                    class="modal-form-input"
                    placeholder="输入参数集名称以保存"
                >
            </div>

            <div class="form-group">
                <label for="batchApiItems">
                    CASE请求体
                    <span class="label-hint">(JSON格式)</span>
                </label>
                <div id="batchApiItems" class="batch-items-container">
                    <!-- API请求项将在这里动态添加 -->
                </div>
            </div>

            <div class="button-group">
                <button type="button" class="save-params-btn" onclick="saveBatchParams()">
                    <span class="btn-icon">💾</span>
                    <span class="btn-text">保存参数</span>
                </button>
                <button type="submit" class="execute-batch-btn">
                    <span class="btn-icon">▶</span>
                    <span class="btn-text">执行请求</span>
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 添加查看内容的模态框 -->
<div id="viewContentModal" class="modal">
    <div class="modal-content">
        <span class="close-modal" onclick="closeViewContentModal()">&times;</span>
        <h2 id="viewContentTitle">内容查看</h2>
        <pre id="viewContentBody" style="white-space: pre-wrap; background: #f8f9fa; padding: 15px; border-radius: 8px; max-height: 500px; overflow-y: auto;"></pre>
    </div>
</div>

<!-- 新增设置模态框 -->
<div id="httpSettingsModal" class="modal">
    <div class="modal-content">
        <span class="close-modal" onclick="closeHttpSettingsModal()">&times;</span>
        <h2>断言设置</h2>
        <form id="httpSettingsForm" class="modal-form">
            <input type="hidden" id="httpScriptName">
            <label for="httpUrl">URL:</label>
            <input type="text" id="httpUrl" required readonly style="background-color: #f0f0f0;">

            <label for="assertType">断言类型:</label>
            <select id="assertType" required>
                <option value="文本">文本</option>
                <option value="正则">正则</option>
                <option value="JSONPath">JSONPath</option>
                <option value="脚本">脚本</option>
            </select>

            <label for="ruleType">规则类型:</label>
            <select id="ruleType" required>
                <option value="包含">包含</option>
                <option value="不包含">不包含</option>
                <option value="等于">等于</option>
            </select>

            <label for="assertBodyType">断言体类型:</label>
            <select id="assertBodyType" required>
                <option value="响应体">响应体</option>
                <option value="响应头">响应头</option>
                <option value="响应码">响应码</option>
            </select>

            <label for="checkInfo">检查信息:</label>
            <input type="text" id="checkInfo" required>

            <button type="submit" class="save-btn">保存</button>
        </form>
    </div>
</div>

<!-- 添加iframe于嵌入API文档 -->
 <div id="apiFrameMask" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 999; background: rgba(0, 0, 0, 0.5);"></div>
<div id="apiFrameContent" style="display: none; justify-content: center; align-items: center; width: 80vw; height: 80vh; position: fixed; top: 5vh;
 left: 5vw; right: 0; bottom: 0; z-index: 1000; background: #fff; padding: 20px; border-radius: 16px;">
    <span class="close-modal" onclick="closeApiFrameContent()">x</span>
    <!-- 添加iframe用于嵌入API文档 -->
    <iframe id="apiFrame" style="width: 80%; height: 100%; border: none; border-radius: 8px;"></iframe>
</div>
<script>
    let currentPage = 1;
    const pageSize = 10;
    let currentScriptName = '';

    async function fetchScripts(page) {
        try {
            console.log('正在请求页码:', page); // 添加日志
            const searchParams = new URLSearchParams({
                page: page,
                page_size: pageSize
            });

            if (currentScriptName) {
                searchParams.append('script_name', currentScriptName);
            }

            const url = `http://127.0.0.1:8080/api/queryScriptList?${searchParams.toString()}`;
            console.log('请求URL:', url); // 记录完整请求URL

            const response = await fetch(url);
            if (!response.ok) {
                throw new Error('网络响应失败');
            }
            const result = await response.json();
            return result;
        } catch (error) {
            console.error('获取脚本列表失败:', error);
            alert('获取脚本列表失败，请检查控制台。');
        }
    }

    function renderScripts(data) {
        const scriptDataDiv = document.getElementById('scriptData');
        // 不清空现有内容，而是追加新内容
        data.forEach(script => {
            const scriptElement = document.createElement('div');
            scriptElement.className = 'script-item';
            scriptElement.innerHTML = `
                <h3 class="script-title">${script.script_name}</h3>
                <div class="script-info-container">
                    <div class="info-grid">
                        <div class="info-item">
                            <span class="info-label">最近一次执行状态:</span>
                            <span class="info-valueV1" style="color: ${
                                script.last_exec_status
                                    ? (script.last_exec_status.includes('失败') || script.last_exec_status.includes('异常')
                                        ? '#dc3545'  // 红色
                                        : script.last_exec_status.includes('成功')
                                            ? '#28a745'  // 绿色
                                            : '#666'     // 默认灰色
                                    )
                                    : '#666'
                            }">${script.last_exec_status || '暂无'}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">指定API前缀:</span>
                            <span class="info-value">${script.need_api || '暂无'}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">执行方式:</span>
                            <span class="info-value">${
                                script.execute_mode
                                    ? (script.execute_mode === 'specified'
                                        ? '按指定时间执行'
                                        : script.execute_mode === 'cycle'
                                            ? '按周期循环执行'
                                            : '暂无')
                                    : '暂无'
                            }</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">执行时间:</span>
                            <span class="info-value">${
                                script.execute_mode === 'cycle'
                                    ? (script.execute_time ? `${script.execute_time}分钟` : '暂无')
                                    : (formatDateTime(script.execute_time) || '暂无')
                            }</span>
                        </div>

                        <div class="info-item full-width">
                            <span class="info-label">所需API集合:</span>
                            <div class="api-tags">
                                ${
                                    script.filtered_apis
                                        ? script.filtered_apis.split('|')
                                            .map(api => `<span class="api-tag">${api.trim()}</span>`)
                                            .join('')
                                        : '<span class="no-data">暂无</span>'
                                }
                            </div>
                        </div>
                        <div class="info-item full-width">
                            <span class="info-label">过滤API集合:</span>
                            <div class="api-tags">
                                ${
                                    script.delete_apis
                                        ? script.delete_apis.split('|')
                                            .map(api => `<span class="api-tag">${api.trim()}</span>`)
                                            .join('')
                                        : '<span class="no-data">暂无</span>'
                                }
                            </div>
                        </div>
                        <div class="info-item">
                            <span class="info-label">创建时间:</span>
                            <span class="info-value">${formatDateTime(script.create_time)}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">更新时间:</span>
                            <span class="info-value">${formatDateTime(script.update_time)}</span>
                        </div>
                    </div>
                </div>
                <div class="action-buttons">
                    <button class="execute-btn" 
                        onclick="executeScript('${script.script_name}')"
                        ${script.script_name.endsWith('_api_test_') ? 'disabled style="background-color: #ccc; cursor: not-allowed;"' : ''}>
                        执行
                    </button>
                    <button class="debug-btn" 
                        onclick="debugScript('${script.script_name}')"
                        ${script.script_name.endsWith('_api_test_') ? 'disabled style="background-color: #ccc; cursor: not-allowed;"' : ''}>
                        调试
                    </button>
                    <button class="report-btn" 
                        onclick="showReport('${script.script_name}')"
                        ${script.script_name.endsWith('_api_test_') ? 'disabled style="background-color: #ccc; cursor: not-allowed;"' : ''}>
                        Trace跟踪
                    </button>
                    <button class="api-btn"
                        onclick="openBatchApi('${script.script_name}')"
                        ${script.script_name.endsWith('_api_test_') ? '' : 'disabled style="background-color: #ccc; cursor: not-allowed;"'}>
                        脚本模拟
                    </button>
                    <button class="log-btn" onclick="showLogs('${script.script_name}')">执行日志</button>
                    <button class="api-list-btn" onclick="showApiList('${script.script_name}')">接口列表</button>
                    <!-- <button class="api-btn" onclick="openApiDocs('${script.script_name}')">Swagger</button> -->
                    <button class="settings-btn" onclick="confirmDelete('${script.id}', '${script.script_name}')" style="background-color: #6c757d;">删除</button>
                    <button class="settings-btn" onclick="openSettings('${script.id}', '${script.script_name}', '${script.execute_time || ''}', '${script.need_api || ''}', '${script.filtered_apis || ''}','${script.delete_apis || ''}', '${script.send_email || ''}', '${script.execute_mode || 'specified'}')">设置</button>

                </div>
            `;
            scriptDataDiv.appendChild(scriptElement);
        });
    }

    async function loadScripts(isNewSearch = false) {
        if (isNewSearch) {
            currentPage = 1;
            const scriptDataDiv = document.getElementById('scriptData');
            scriptDataDiv.innerHTML = ''; // 清空现有列表

            // 重置加载更多按钮状态getBatchParams
            const loadMoreBtn = document.getElementById('loadMore');
            loadMoreBtn.disabled = false;
            loadMoreBtn.style.backgroundColor = ''; // 恢复默认背景色
            loadMoreBtn.style.cursor = 'pointer';
            loadMoreBtn.textContent = '加载更多';
        }

        console.log('加载脚本页码:', currentPage); // 添加日志
        const result = await fetchScripts(currentPage);
        if (result) {
            // 检查是否有数据
            if (result.data && result.data.length > 0) {
                renderScripts(result.data);
                currentPage++; // 在成功获取数据后递增页码
                console.log('页码已更新为:', currentPage); // 添加日志

                // 如果返回的数据量小于页大小，说明已经没有更多数据
                if (result.data.length < pageSize) {
                    document.getElementById('loadMore').disabled = true;
                    document.getElementById('loadMore').style.backgroundColor = '#ccc';
                    document.getElementById('loadMore').style.cursor = 'not-allowed';
                    document.getElementById('loadMore').textContent = '没有更多数据';
                }
            } else {
                // 没有数据，禁用按钮
                document.getElementById('loadMore').disabled = true;
                document.getElementById('loadMore').style.backgroundColor = '#ccc';
                document.getElementById('loadMore').style.cursor = 'not-allowed';
                document.getElementById('loadMore').textContent = '没有更多数据';

                if (currentPage === 1) {
                    // 如果是第一页就没有数据，显示提示信息
                    const scriptDataDiv = document.getElementById('scriptData');
                    scriptDataDiv.innerHTML = '<div style="text-align:center;padding:20px;color:#666;">没有找到符合条件的脚本</div>';
                }
            }
        }
    }

    // 搜索按钮点击事件
    document.getElementById('searchButton').addEventListener('click', () => {
        currentScriptName = document.getElementById('searchScriptName').value.trim();
        loadScripts(true);
    });

    // 搜索框回车事件
    document.getElementById('searchScriptName').addEventListener('keypress', (event) => {
        if (event.key === 'Enter') {
            currentScriptName = event.target.value.trim();
            loadScripts(true);
        }
    });

    // 页面加载时自动加载第一页脚本
    window.onload = () => {
        loadScripts(true); // 使用true参数确保初始化按钮状态
    };

    // 加载更多按钮
    document.getElementById('loadMore').addEventListener('click', function() {
        console.log('点击加载更多，当前页码:', currentPage); // 添加日志
        loadScripts();
    });

    // 表单提交时
    document.getElementById('uploadForm').addEventListener('submit', async (event) => {
        event.preventDefault(); // 防止默认表单提交

        const formData = new FormData(event.target);
        const response = await fetch(event.target.action, {
            method: 'POST',
            body: formData
        });

        if (response.ok) {
            alert('文件生成成功！');
            currentPage = 1; // 重置为第一页
            loadScripts(); // 重新加载脚本列表
        } else {
            alert('文件生成失败，请检查输入。');
        }
    });

    // 执行脚本
    async function executeScript(scriptName) {
        try {
            const response = await fetch(`http://127.0.0.1:8080/api/execute?name=${encodeURIComponent(scriptName)}`);
            if (!response.ok) {
                throw new Error('网络请求失败');
            }

            const result = await response.json();

            // 根据返回的 success 状态显示对应的消息
            if (result.success) {
                alert('执行成功：' + result.message);
            } else {
                alert('执行失败：' + result.message);
            }

            // 无论成功失败都刷新列表
            loadScripts(true);

        } catch (error) {
            console.error('执行脚本失败:', error);
            alert('执行脚本失败：' + error.message);
        }
    }

    // 打开设置模态框
    function openSettings(id, scriptName, executeTime, needApi, filteredApis, deleteApis, sendEmail, executeMode) {
        const modal = document.getElementById('settingsModal');
        document.getElementById('scriptId').value = id;
        document.getElementById('modalScriptName').value = scriptName;
        document.getElementById('modalNeedApi').value = needApi;
        document.getElementById('modalFilteredApis').value = filteredApis;
        document.getElementById('modalDeleteApis').value = deleteApis;
        document.getElementById('modalSendEmail').value = sendEmail || '';
        document.getElementById('modalExecuteMode').value = executeMode || 'specified';
        
        // 根据执行方式设置时间输入框
        if (executeMode === 'cycle') {
            document.getElementById('modalCycleTime').value = executeTime || '';
            document.getElementById('specifiedTimeGroup').style.display = 'none';
            document.getElementById('cycleTimeGroup').style.display = 'block';
        } else {
            document.getElementById('modalExecuteTime').value = executeTime ? formatDateTimeForInput(executeTime) : '';
            document.getElementById('specifiedTimeGroup').style.display = 'block';
            document.getElementById('cycleTimeGroup').style.display = 'none';
        }
        
        modal.style.display = 'flex';
    }

    // 关闭设置模态框
    function closeSettingsModal() {
        document.getElementById('settingsModal').style.display = 'none';
    }

    // 关闭日志模态框
    function closeLogModal() {
        document.getElementById('logModal').style.display = 'none';
    }


            // 添加日期格式化函数用于datetime-local输入框
    function formatDateTimeForInput(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
    }
    // 点击模态框外部关闭
    window.onclick = function(event) {
        const logModal = document.getElementById('logModal');
        const settingsModal = document.getElementById('settingsModal');
        const apiModal = document.getElementById('apiModal');
        const batchApiModal = document.getElementById('batchApiModal');

        if (event.target == logModal) {
            logModal.style.display = 'none';
        }
        if (event.target == settingsModal) {
            settingsModal.style.display = 'none';
        }
        if (event.target == apiModal) {
            closeApiModal();
        }
        if (event.target == batchApiModal) {
            closeBatchApiModal();
        }
    }

    // 修改表单提交处理
    document.getElementById('settingsForm').onsubmit = async function(e) {
        e.preventDefault();
        const executeMode = document.getElementById('modalExecuteMode').value;
        const data = {
            script_name: document.getElementById('modalScriptName').value,
            need_api: document.getElementById('modalNeedApi').value,
            filtered_apis: document.getElementById('modalFilteredApis').value,
            delete_apis: document.getElementById('modalDeleteApis').value,
            send_email: document.getElementById('modalSendEmail').value,
            execute_mode: executeMode
        };

        // 根据执行方式设置不同的时间字段
        if (executeMode === 'specified') {
            data.execute_time = document.getElementById('modalExecuteTime').value;
        } else {
            data.execute_time = document.getElementById('modalCycleTime').value;
        }

        try {
            const scriptId = document.getElementById('scriptId').value;
            const response = await fetch(`http://127.0.0.1:8080/api/updateScript/${scriptId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });

            if (!response.ok) {
                throw new Error('更新失败');
            }

            alert('更新成功！');
            document.getElementById('settingsModal').style.display = 'none';
            loadScripts(true);
        } catch (error) {
            console.error('更新脚本设置失败:', error);
            alert('更新失败，请检查控制台。');
        }
    };

    // Debug脚本
    async function debugScript(scriptName) {
        try {
            const response = await fetch(`http://127.0.0.1:8080/api/debug?trace=${encodeURIComponent(scriptName)}`);
            if (!response.ok) {
                throw new Error('网络请求失败');
            }

            const result = await response.json();

            // 根据返回的 success 状态显示对应的消息
            if (result.success) {
                alert('Debug成功：' + result.message);
            } else {
                alert('Debug失败：' + result.message);
            }

            // 无论成功失败都刷新列表
            loadScripts(true);

        } catch (error) {
            console.error('Debug脚本失败:', error);
            alert('Debug脚本失败：' + error.message);
        }
    }

    // 显示报告
    async function showReport(scriptName) {
        try {
            const response = await fetch(`http://127.0.0.1:8080/api/showTrace?trace=${encodeURIComponent(scriptName)}`);
            if (!response.ok) {
                throw new Error('网络请求失败');
            }

            const result = await response.json();

            // 根据返回的 success 状态显示对应的消息
            if (result.success) {
                alert('获取报告成功：' + result.message);
            } else {
                alert('获取报告失败：' + result.message);
            }

            // 无论成功失败都刷新列表
            loadScripts(true);

        } catch (error) {
            console.error('获取报告失败:', error);
            alert('获取报告失败：' + error.message);
        }
    }

    // 获取脚本功能
    document.getElementById('generateScript').addEventListener('click', async () => {
        const url = document.getElementById('scriptUrl').value.trim();

        if (!url) {
            alert('请输入URL');
            return;
        }

        try {
            const response = await fetch(`http://127.0.0.1:8080/api/codegen?url=${encodeURIComponent(url)}`);
            if (!response.ok) {
                throw new Error('网络请求失败');
            }

            const result = await response.json();

            // 根据返回的 success 状态显示对应的消息
            if (result.success) {
                alert('获取脚本成功：' + result.message);
                // 成功后清空输入框
                document.getElementById('scriptUrl').value = '';
                // 刷新脚本列表
                loadScripts(true);
            } else {
                alert('获取脚本失败：' + result.message);
            }

        } catch (error) {
            console.error('获取脚本失败:', error);
            alert('获取脚本失败：' + error.message);
        }
    });

    // 为URL输入框添加回车事件
    document.getElementById('scriptUrl').addEventListener('keypress', (event) => {
        if (event.key === 'Enter') {
            document.getElementById('generateScript').click();
        }
    });

    // 打开API文档
    function openApiDocs(scriptName) {
        console.log('Function called with scriptName:', scriptName);
        const url = `http://127.0.0.1:8080/api/docs#/default/execute_execute_post`;
        const apiFrame = document.getElementById('apiFrame'); // 获取iframe元素
        apiFrame.src = url; // 设置iframe的src属性
        const apiFrameContent = document.getElementById('apiFrameContent'); // 获取iframe内容容器
        apiFrameContent.style.display = 'flex'; // 显示iframe
        const apiFrameMask = document.getElementById('apiFrameMask'); // 获取遮罩层元素
        apiFrameMask.style.display = 'block'; // 显示遮罩层
    }
    function closeApiFrameContent() {
        const apiFrameContent = document.getElementById('apiFrameContent'); // 获取iframe内容容器
        apiFrameContent.style.display = 'none'; // 隐藏iframe
        const apiFrameMask = document.getElementById('apiFrameMask'); // 获取遮罩层元素
        apiFrameMask.style.display = 'none'; // 隐藏遮罩层
    }

    // 日志相关变量
    let currentLogPage = 1;
    let currentScriptNameForLog = '';
    let totalPages = 0;
    const logPageSize = 10;

    // 显示日志弹窗
    function showLogs(scriptName) {
        currentLogPage = 1;
        currentScriptNameForLog = scriptName;
        const modal = document.getElementById('logModal');
        modal.style.display = 'flex';
        fetchLogs();
    }

    // 获取日志数据
    async function fetchLogs() {
        try {
            const response = await fetch(
                `http://127.0.0.1:8080/api/queryScriptLogList?page=${currentLogPage}&page_size=${logPageSize}&script_name=${encodeURIComponent(currentScriptNameForLog)}`
            );

            if (!response.ok) {
                throw new Error('获取日志失败');
            }

            const result = await response.json();
            totalPages = Math.ceil(result.total / logPageSize);
            renderLogs(result);
            updatePagination();
        } catch (error) {
            console.error('获取日志失败:', error);
            alert('获取日志失败：' + error.message);
        }
    }

    // 渲染日志列表
    function renderLogs(data) {
        const logList = document.getElementById('logList');
        logList.innerHTML = '';

        data.data.forEach(log => {
            const logItem = document.createElement('div');
            logItem.className = 'log-item';

            // 判断状态颜色
            const statusClass = log.status.includes('成功') ? 'success'
                            : (log.status.includes('失败') || log.status.includes('异常')) ? 'error'
                            : '';

            logItem.innerHTML = `
                <div class="log-status ${statusClass}">
                    状态: ${log.status}
                </div>
                <div class="log-details">
                    <div data-label="运行方式:">${log.mode}</div>
                    <div data-label="请求参数(post):">${log.post_data}</div>
                    <div data-label="结果信息:">${log.msg}</div>
                    <div data-label="创建时间:">${formatDateTime(log.create_time)}</div>
                    <div data-label="更新时间:">${formatDateTime(log.update_time)}</div>
                </div>
            `;
            logList.appendChild(logItem);
        });
    }

    // 更新分页信息
    function updatePagination() {
        document.getElementById('pageInfo').textContent = `第 ${currentLogPage} 页 / 共 ${totalPages} 页`;
        document.getElementById('prevPage').disabled = currentLogPage === 1;
        document.getElementById('nextPage').disabled = currentLogPage === totalPages;
    }

    // 切换页面
    async function changePage(delta) {
        const newPage = currentLogPage + delta;
        if (newPage >= 1 && newPage <= totalPages) {
            currentLogPage = newPage;
            await fetchLogs();
        }
    }

    // 接口列表相关变量
    let currentApiPage = 1;
    let currentScriptNameForApi = '';
    let totalApiPages = 0;
    const apiPageSize = 10;

    // 显示接口列表
    async function showApiList(scriptName) {
        currentApiPage = 1;
        currentScriptNameForApi = scriptName;
        document.getElementById('apiModal').style.display = 'flex';
        await fetchApiList();
    }

    // 关闭接口列表模态框
    function closeApiModal() {
        document.getElementById('apiModal').style.display = 'none';
    }

    // 获取接口列表数据
    async function fetchApiList() {
        try {
            const response = await fetch(
                `http://127.0.0.1:8080/api/queryLogHttpList?page=${currentApiPage}&page_size=${apiPageSize}&script_name=${encodeURIComponent(currentScriptNameForApi)}`
            );

            if (!response.ok) {
                throw new Error('获取接口列表失败');
            }

            const result = await response.json();
            totalApiPages = Math.ceil(result.total / apiPageSize);
            renderApiList(result);
            updateApiPagination();
        } catch (error) {
            console.error('获取接口列表失败:', error);
            alert('获取接口列表失败：' + error.message);
        }
    }

    // 渲染接口列表
    function renderApiList(data) {
        const apiList = document.getElementById('apiList');
        apiList.innerHTML = '';

        data.data.forEach(api => {

            const apiItem = document.createElement('div');
            apiItem.style.backgroundColor = api.status === 200 ? 'transparent' : '#ffcccc'
            apiItem.className = `api-item ${api.status !== 200 ? 'error' : ''}`;
            apiItem.innerHTML = `
                <div class="api-header">
                     <button class="settings-btn" style="background-color: #28a745; color: white;" onclick="openHttpSettings('${api.script_name}', '${api.url}')">断言设置</button>
                    <span class="api-status ${api.status === 200 ? 'success' : 'error'}">
                        状态码: ${api.status}
                    </span>

                </div>
                <div class="api-detail-row">
                    <span>唯一标识:</span>
                    <span>${api.unique_code}</span>
                </div>
                <div class="api-detail-row">
                    <span>请求URL:</span>
                    <span>${api.url}</span>
                </div>
                <div class="api-detail-row">
                    <span>请求方式:</span>
                    <span>${api.method}</span>
                </div>
                <div class="api-detail-row">
                    <span>POST请求参数:</span>
                    <span>${api.post_data ? api.post_data : '暂无'}</span>
                </div>
                <div class="api-detail-row">
                    <span>接口响应:</span>
                    <span style="color: ${
                        api.response_time > 500 ? '#e90e0e' :
                        api.response_time > 300 ? '#ad686f' :
                        '#28a745'
                    }; font-weight: bold;">${api.response_time}ms</span>
                </div>
                <div class="api-detail-row">
                    <span>请求头:</span>
                    <div class="button-group" style="justify-content: center;">
                        <button class="copy-btn" onclick="copyContent('${encodeURIComponent(api.headers)}', this)" style="justify-content: center;">复制</button>
                        <button class="view-btn" onclick="viewContent('请求头', '${encodeURIComponent(api.headers)}')" style="justify-content: center;">查看</button>
                    </div>
                </div>
                <div class="api-detail-row">
                    <span>响应体:</span>
                    <div class="button-group" style="justify-content: center;">
                        <button class="copy-btn" onclick="copyContent('${encodeURIComponent(api.body)}', this)" style="justify-content: center;">复制</button>
                        <button class="view-btn" onclick="viewContent('响应体', '${encodeURIComponent(api.body)}')" style="justify-content: center;">查看</button>
                    </div>
                </div>
                <div class="api-detail-row">
                    <span>响应头:</span>
                    <div class="button-group" style="justify-content: center;">
                        <button class="copy-btn" onclick="copyContent('${encodeURIComponent(api.response_header)}', this)" style="justify-content: center;">复制</button>
                        <button class="view-btn" onclick="viewContent('响应头', '${encodeURIComponent(api.response_header)}')" style="justify-content: center;">查看</button>
                    </div>
                </div>
                <div class="api-detail-row">
                    <span>创建时间:</span>
                    <span class="api-timestamp">${formatDateTime(api.create_time)}</span>
                </div>
                <div class="api-detail-row">
                    <span>更新时间:</span>
                    <span class="api-timestamp">${formatDateTime(api.update_time)}</span>
                </div>
            `;
            apiList.appendChild(apiItem);
        });
    }

    // 复制内容功能
    async function copyContent(content, button) {
        try {
            console.error('内容:', content);
            const decodedContent = decodeURIComponent(content);

            // 检查内容是否为空
            if (!decodedContent) {
                alert('当前数据为空，无法复制！');
                return;
            }

            await navigator.clipboard.writeText(decodedContent);
            button.textContent = '已复制';
            button.classList.add('copied');
            setTimeout(() => {
                button.textContent = '复制';
                button.classList.remove('copied');
            }, 2000);
        } catch (err) {
            console.error('复制失败:', err);
            alert('复制失败');
        }
    }

    // 更新分页信息
    function updateApiPagination() {
        document.getElementById('apiPageInfo').textContent = `第 ${currentApiPage} 页 / 共 ${totalApiPages} 页`;
        document.getElementById('apiPrevPage').disabled = currentApiPage === 1;
        document.getElementById('apiNextPage').disabled = currentApiPage === totalApiPages;
    }

    // 切换页面
    async function changeApiPage(delta) {
        const newPage = currentApiPage + delta;
        if (newPage >= 1 && newPage <= totalApiPages) {
            currentApiPage = newPage;
            await fetchApiList();
        }
    }

    // 点击模态框外部关闭
    window.onclick = function(event) {
        const apiModal = document.getElementById('apiModal');
        if (event.target == apiModal) {
            closeApiModal();
        }
    }

    // 添加时间格式化函数
    function formatDateTime(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    // 修改switchTab函数，避免AI版标签页的切换效果
    function switchTab(tabIndex) {
        const tabButtons = document.querySelectorAll('.tab-button');
        tabButtons.forEach((button, index) => {
            if (index === tabIndex) {
                button.classList.add('active');
            } else {
                button.classList.remove('active');
            }
        });

        const tabContents = document.querySelectorAll('.tab-content');
        tabContents.forEach((content, index) => {
            if (index === tabIndex) {
                content.classList.add('active');
            } else {
                content.classList.remove('active');
            }
        });
    }

    // 打开批量API模态框
    function openBatchApi(scriptName) {
        const modal = document.getElementById('batchApiModal');
        document.getElementById('scriptName').value = scriptName; // 设置API名称
        modal.style.display = 'flex';

        // 清空现有项并添加第一个请求项
        const itemsContainer = document.getElementById('batchApiItems');
        itemsContainer.innerHTML = '';
        addApiItem(scriptName);

        // 清空参数集名称
        document.getElementById('paramsName').value = '';

        // 加载该脚本的参数集
        loadBatchParams();
    }

    // 加载批量执行参数列表
    async function loadBatchParams() {
        const scriptName = document.getElementById('scriptName').value;
        if (!scriptName) {
            console.error('脚本名称为空');
            return;
        }

        try {
            // 添加更多日志来帮助调试
            console.log('正在获取参数列表，脚本名称:', scriptName);

            // 确保URL编码正确
            const encodedScriptName = encodeURIComponent(scriptName);
            const url = `http://127.0.0.1:8080/api/getBatchParams?script_name=${encodedScriptName}`;
            console.log('请求URL:', url);

            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`HTTP错误，状态码: ${response.status}`);
            }

            const result = await response.json();
            console.log('获取参数列表结果:', result);

            if (result.success) {
                const paramsSelect = document.getElementById('paramsSelect');
                // 保留第一个默认选项
                paramsSelect.innerHTML = '<option value="">-- 选择已保存的参数集 --</option>';

                // 添加参数集选项
                if (result.data && Array.isArray(result.data)) {
                    result.data.forEach(param => {
                        const option = document.createElement('option');
                        option.value = param.id;
                        option.textContent = param.params_name;
                        option.dataset.params = param.params_data;
                        paramsSelect.appendChild(option);
                    });
                } else {
                    console.warn('返回的数据不是数组:', result.data);
                }
            } else {
                console.error('加载参数集失败:', result.message);
                alert(`加载参数集失败: ${result.message}`);
            }
        } catch (error) {
            console.error('加载参数集异常:', error);
            alert(`加载参数集异常: ${error.message}`);
        }
    }

    // 保存批量执行参数
    async function saveBatchParams() {
        const scriptName = document.getElementById('scriptName').value;
        const paramsName = document.getElementById('paramsName').value.trim();
        const items = document.querySelectorAll('.batch-api-input');

        // 验证输入
        if (!scriptName) {
            alert('脚本名称不能为空');
            return;
        }

        if (!paramsName) {
            alert('请输入参数集名称');
            return;
        }

        const dataList = [];

        // 收集所有请求项的数据
        for (const item of items) {
            try {
                const itemValue = item.value.trim();
                if (itemValue) {
                    const jsonData = JSON.parse(itemValue);
                    dataList.push(jsonData);
                }
            } catch (error) {
                alert('JSON格式错误，请检查输入！');
                return;
            }
        }

        if (dataList.length === 0) {
            alert('请至少添加一个有效的请求参数');
            return;
        }

        try {
            const response = await fetch('http://127.0.0.1:8080/api/saveBatchParams', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    script_name: scriptName,
                    params_name: paramsName,
                    params_data: JSON.stringify(dataList)
                })
            });

            const result = await response.json();

            if (result.success) {
                alert(result.message);
                // 重新加载参数集列表
                loadBatchParams();
            } else {
                alert(`保存失败: ${result.message}`);
            }
        } catch (error) {
            console.error('保存参数失败:', error);
            alert('保存参数时发生错误: ' + error.message);
        }
    }

    // 查看内容功能
    function viewContent(title, content) {
        try {
            const decodedContent = decodeURIComponent(content);

            // 检查内容是否为空
            if (!decodedContent) {
                alert('当前数据为空，无法查看！');
                return;
            }

            const modal = document.getElementById('viewContentModal');
            const titleElement = document.getElementById('viewContentTitle');
            const bodyElement = document.getElementById('viewContentBody');

            titleElement.textContent = title;

            // 尝试格式化 JSON
            try {
                const jsonContent = JSON.parse(decodedContent);
                bodyElement.textContent = JSON.stringify(jsonContent, null, 2);
            } catch {
                // 如果不是 JSON，直接显示原文
                bodyElement.textContent = decodedContent;
            }

            modal.style.display = 'flex';
        } catch (error) {
            console.error('查看内容失败:', error);
            alert('查看内容失败');
        }
    }

    function closeViewContentModal() {
        document.getElementById('viewContentModal').style.display = 'none';
    }

    // 点击模态框外部关闭
    window.onclick = function(event) {
        const viewContentModal = document.getElementById('viewContentModal');
        if (event.target == viewContentModal) {
            viewContentModal.style.display = 'none';
        }
    }

    // 校验文件名称
    function validateFilename(input) {
        const value = input.value;
        const errorMessage = document.getElementById('filenameError');

        if (value && !value.endsWith('test_') && !value.endsWith('_api_test_')) {
            errorMessage.textContent = '文件名称必须以 "test_" 或 "_api_test_" 结尾';
        } else {
            errorMessage.textContent = '';
        }
    }

    function validateFilenameBeforeSubmit() {
        const filenameInput = document.querySelector('input[name="filename"]');
        let filename = filenameInput.value.trim();
        
        // 如果文件名不是以test_结尾，自动添加test_后缀
        if (!filename.endsWith('test_') && !filename.endsWith('_api_test_')) {
            filename += 'test_';
            filenameInput.value = filename;
        }
        
        // 获取复选框的值
        const genLoginChecked = document.getElementById('gen_login').checked;
        const useLoginChecked = document.getElementById('use_login').checked;

        const formData = new FormData(document.getElementById('uploadForm'));
        formData.append('genLogin', genLoginChecked ? 'true' : 'false');
        formData.append('useLogin', useLoginChecked ? 'true' : 'false');

        fetch('http://127.0.0.1:8080/api/upload', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (response.ok) {
                alert('文件生成成功！');
                loadScripts(true);
            } else {
                alert('文件生成失败，请检查输入。');
            }
        });
    }

    // 新增打开设置模态框的函数
    function openHttpSettings(scriptName, url) {
        document.getElementById('httpScriptName').value = scriptName;
        document.getElementById('httpUrl').value = url;

        // 请求设置接口
        fetch('http://127.0.0.1:8080/api/queryHttpSettingInfo', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ script_name: scriptName, url: url })
        })
        .then(response => response.json())
        .then(data => {
            if (data.setting) {
                document.getElementById('httpUrl').value = data.setting.url;
                document.getElementById('assertType').value = data.setting.assert_type;
                document.getElementById('ruleType').value = data.setting.rule_type;
                document.getElementById('assertBodyType').value = data.setting.assert_body_type;
                document.getElementById('checkInfo').value = data.setting.check_info;
            }
            document.getElementById('httpSettingsModal').style.display = 'flex';
        })
        .catch(error => {
            console.error('获取设置失败:', error);
            alert('获取设置失败，请检查控制台。');
        });
    }

    // 新增关闭设置模态框的函数
    function closeHttpSettingsModal() {
        document.getElementById('httpSettingsModal').style.display = 'none';
    }

    // 新增处理设置表单提交的函数
    document.getElementById('httpSettingsForm').onsubmit = async function(e) {
        e.preventDefault();
        const data = {
            script_name: document.getElementById('httpScriptName').value,
            url: document.getElementById('httpUrl').value,
            assert_type: document.getElementById('assertType').value,
            rule_type: document.getElementById('ruleType').value,
            assert_body_type: document.getElementById('assertBodyType').value,
            check_info: document.getElementById('checkInfo').value
        };

        try {
            const response = await fetch('http://127.0.0.1:8080/api/updateHttpSettingInfo', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });

            if (!response.ok) {
                throw new Error('更新失败');
            }

            alert('更新成功！');
            closeHttpSettingsModal();
        } catch (error) {
            console.error('更新设置失败:', error);
            alert('更新失败，请检查控制台。');
        }
    };

    // 添加删除确认函数
    function confirmDelete(scriptId, scriptName) {
        if (confirm(`确定要删除脚本 "${scriptName}" 吗？此操作不可恢复。`)) {
            deleteScript(scriptId, scriptName);
        }
    }

    // 添加删除脚本函数
    async function deleteScript(scriptId, scriptName) {
        try {
            const response = await fetch(`http://127.0.0.1:8080/api/deleteScript/${scriptId}?script_name=${scriptName}`, {
                method: 'DELETE',
                headers: {
                    'accept': 'application/json'
                }
            });

            const result = await response.json();

            if (response.ok) {
                alert(result.message);
                // 删除成功后刷新脚本列表
                loadScripts(true);
            } else {
                throw new Error(result.message || '删除失败');
            }
        } catch (error) {
            console.error('删除脚本失败:', error);
            alert('删除脚本失败：' + error.message);
        }
    }

    // 添加切换执行时间输入框的函数
    function toggleExecuteTimeInput() {
        const executeMode = document.getElementById('modalExecuteMode').value;
        const specifiedTimeGroup = document.getElementById('specifiedTimeGroup');
        const cycleTimeGroup = document.getElementById('cycleTimeGroup');
        
        if (executeMode === 'specified') {
            specifiedTimeGroup.style.display = 'block';
            cycleTimeGroup.style.display = 'none';
        } else {
            specifiedTimeGroup.style.display = 'none';
            cycleTimeGroup.style.display = 'block';
        }
    }

    // 处理批量API请求表单提交
    document.addEventListener('DOMContentLoaded', function() {
        // 监听参数集选择变化
        document.getElementById('paramsSelect').addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            if (selectedOption.value) {
                try {
                    // 获取参数数据并填充到请求项中
                    const paramsData = JSON.parse(selectedOption.dataset.params);

                    // 清空现有请求项
                    const itemsContainer = document.getElementById('batchApiItems');
                    itemsContainer.innerHTML = '';

                    // 填充参数数据
                    paramsData.forEach((param, index) => {
                        if (index > 0) {
                            addApiItem(); // 添加额外的请求项
                        } else {
                            addApiItem(); // 添加第一个请求项
                        }
                    });

                    // 设置参数值
                    const inputElements = document.querySelectorAll('.batch-api-input');
                    paramsData.forEach((param, index) => {
                        if (index < inputElements.length) {
                            inputElements[index].value = JSON.stringify(param, null, 2);
                        }
                    });

                    // 设置参数集名称
                    document.getElementById('paramsName').value = selectedOption.textContent;

                } catch (error) {
                    console.error('解析参数数据失败:', error);
                    alert('加载参数数据失败');
                }
            }
        });
    });

    // 处理批量API请求表单提交
    function closeBatchApiModal() {
        document.getElementById('batchApiModal').style.display = 'none';
    }

    // 添加API请求项
    function addApiItem() {
        const itemsContainer = document.getElementById('batchApiItems');
        const newItem = document.createElement('div');
        newItem.className = 'batch-api-item';
        newItem.innerHTML = `
            <textarea class="batch-api-input" placeholder='{"key": "value"}'></textarea>
            <div class="batch-api-controls">
                <button type="button" class="add-api-btn" onclick="addApiItem()">+</button>
                <button type="button" class="remove-api-btn" onclick="removeApiItem(this)">-</button>
            </div>
        `;
        itemsContainer.appendChild(newItem);
    }

    // 移除API请求项
    function removeApiItem(button) {
        const items = document.querySelectorAll('.batch-api-item');
        if (items.length > 1) {
            button.closest('.batch-api-item').remove();
        } else {
            alert('至少需要保留一个请求项');
        }
    }

    // 处理批量API请求表单提交
    document.getElementById('batchApiForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const scriptName = document.getElementById('scriptName').value;
        const items = document.querySelectorAll('.batch-api-input');
        const dataList = [];

        // 收集所有请求项的数据
        for (const item of items) {
            try {
                const itemValue = item.value.trim();
                if (itemValue) {
                    const jsonData = JSON.parse(itemValue);
                    dataList.push(jsonData);
                }
            } catch (error) {
                alert('JSON格式错误，请检查输入！');
                return;
            }
        }

        if (dataList.length === 0) {
            alert('请至少添加一个有效的请求参数');
            return;
        }

        try {
            const response = await fetch('http://127.0.0.1:8080/api/batchExecute', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    script_name: scriptName,
                    data_list: dataList
                })
            });

            const result = await response.json();

            if (result.success) {
                alert(result.message);
                closeBatchApiModal();
            } else {
                alert(`执行失败: ${result.message}`);
            }
        } catch (error) {
            console.error('批量执行失败:', error);
            alert('批量执行时发生错误: ' + error.message);
        }
    });

    // 关闭查看内容模态框
    function closeViewContentModal() {
        document.getElementById('viewContentModal').style.display = 'none';
    }

    // 查看内容
    function viewContent(title, content) {
        const decodedContent = decodeURIComponent(content);
        document.getElementById('viewContentTitle').textContent = title;
        document.getElementById('viewContentBody').textContent = decodedContent;
        document.getElementById('viewContentModal').style.display = 'flex';
    }

    // 关闭HTTP设置模态框
    function closeHttpSettingsModal() {
        document.getElementById('httpSettingsModal').style.display = 'none';
    }

    // 打开HTTP设置模态框
    function openHttpSettings(scriptName, url) {
        document.getElementById('httpScriptName').value = scriptName;
        document.getElementById('httpUrl').value = url;
        document.getElementById('httpSettingsModal').style.display = 'flex';
    }

    function validateApiFileName() {
        const filenameInput = document.querySelector('input[name="filename"]');
        let filename = filenameInput.value.trim();
        
        // 如果文件名已经以_api_test_结尾，不做修改
        if (filename.endsWith('_api_test_')) {
            // 直接生成API文件
            generateApiFile();
            return;
        }
        
        // 如果文件名以test_结尾，替换为_api_test_
        if (filename.endsWith('test_')) {
            filename = filename.substring(0, filename.length - 5) + '_api_test_';
        } else {
            // 否则直接添加_api_test_后缀
            filename += '_api_test_';
        }
        
        // 更新输入框的值
        filenameInput.value = filename;
        
        // 继续执行生成API文件的逻辑
        generateApiFile();
    }

    function generateApiFile() {
        const formData = new FormData(document.getElementById('uploadForm'));
        formData.append('fileType', 1); // 添加额外参数

        // 获取复选框的值
        const genLoginChecked = document.getElementById('gen_login').checked;
        const useLoginChecked = document.getElementById('use_login').checked;
        formData.append('genLogin', genLoginChecked ? 'true' : 'false');
        formData.append('useLogin', useLoginChecked ? 'true' : 'false');

        fetch('http://127.0.0.1:8080/api/upload', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (response.ok) {
                alert('文件生成成功！');
                loadScripts(true);
            } else {
                alert('文件生成失败，请检查输入。');
            }
        });
    }
</script>
</body>
</html>